<template>
  <view class="container">
    <view>
      <u--form
        labelPosition="left"
        :model="form"
        :rules="rules"
        ref="form"
        labelWidth="90px"
        :labelStyle="labelStyle"
      >
        <view class="title"> 基础信息 </view>
        <view class="box">
          <u-form-item label="证书名称" prop="zsmc" borderBottom>
            <u--input
              v-model="form.zsmc"
              placeholder="输入证书名称"
              border="none"
            ></u--input>
          </u-form-item>
          <u-form-item label="证书编号" prop="zsbh" borderBottom>
            <u--input
              v-model="form.zsbh"
              placeholder="输入证书编号"
              border="none"
            ></u--input>
          </u-form-item>
          <u-form-item label="证书类型" prop="zslx" borderBottom>
            <u--input
              v-model="form.zslx"
              placeholder="输入证书类型"
              border="none"
            ></u--input>
          </u-form-item>
          <u-form-item label="有效日期" prop="yxrq" borderBottom @click="show = true">
            <u--input
              v-model="form.yxrq"
              placeholder="请选择日期"
              disabledColor="#ffffff"
              disabled
              border="none"
            ></u--input>
            <u-icon
              slot="right"
              name="arrow-right"

            ></u-icon>
          </u-form-item>
          <u-calendar :show="show" mode="range" @confirm="confirm"></u-calendar>
          <u-form-item label="发证机构" prop="fzjg" borderBottom>
            <u--input
              v-model="form.fzjg"
              placeholder="输入发证机构"
              border="none"
            ></u--input>
          </u-form-item>
          <u-form-item label="添加证书照片" borderBottom>
            <!-- <u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
							:maxCount="1"></u-upload> -->
            <view
              class="imageBigBox"
              v-for="(item, i) in imageList"
              :key="i"
              style="
                display: flex;
                justify-content: center;
                flex-direction: column;
                align-items: center;
              "
            >
              <image
                style="width: 200rpx; height: 200rpx"
                @click="previewImg(item)"
                :src="item"
              ></image>
              <u-icon
                class="delIcon"
                name="close-circle"
                color="#999"
                size="25"
                @click="delectImg(i)"
              >
              </u-icon>
            </view>
            <view
              class="uoloadImg-box"
              @click="chooseFile"
              v-if="imageList.length < 1"
            >
              <view
                class="jia"
                style="
                  width: 200rpx;
                  height: 200rpx;
                  display: flex;
                  justify-content: center;
                  align-items: center;
                "
              >
                <image
                  style="width: 90rpx; height: 80rpx"
                  src="../../static/image/photo.png"
                  mode=""
                >
                </image>
              </view>
            </view>
          </u-form-item>

          <u-form-item label="" prop="zsms" borderBottom>
            <view class="textarea">
              <text class="one">证书描述</text>
              <view class="tarea">
                <textarea
                  style="
                    background-color: #f6f6f6;
                    color: #666666;
                    font-size: 28rpx;
                    border-radius: 8rpx;
                    padding: 24rpx;
                  "
                  v-model="form.zsms"
                  placeholder="请输入……"
                  rows="3"
                ></textarea>
              </view>
            </view>
          </u-form-item>
        </view>
      </u--form>
      <u-button
        type="primary"
        text="确认"
        @click="submit"
        class="but"
      ></u-button>
    </view>
  </view>
</template>

<script>
import { add } from "@/api/certificate";
import { URL } from "@/api/request.js";
export default {
  data() {
    return {
      showSex: false,
      show: false,
      labelStyle: {
        color: "#666",
      },
      fileList1: [],
      imageList: [], //本地上传图片数组
      list: [], //上传后端后返回的图片链接数组
      form: {
        xgfj: "",
        yxrq: "",
        zsmc: "",
        zsbh: "",
        zslx: "",
        zsms: "",
        fzjg: "",
      },

      rules: {
        xgfj: {
          type: "string",
          required: true,
          message: "不能为空",
          trigger: ["blur", "change"],
        },
        zsbh: {
          type: "string",
          required: true,
          message: "不能为空",
          trigger: ["blur", "change"],
        },
        zslx: {
          type: "string",
          required: true,
          message: "不能为空",
          trigger: ["blur", "change"],
        },
        zsmc: {
          type: "string",
          required: true,
          message: "不能为空",
          trigger: ["blur", "change"],
        },
        zsms: {
          type: "string",
          required: true,
          message: "不能为空",
          trigger: ["blur", "change"],
        },
        yxrq: {
          type: "string",
          required: true,
          message: "不能为空",
          trigger: ["blur", "change"],
        },
      },
    };
  },
  onShow() {
  	this.form.userid=uni.getStorageSync('userId')
  },
  methods: {
    async chooseFile() {
      let that = this;
      uni.chooseImage({
        count: 1, //图片大于1可以多选,这样可以不超出最大上传值
        sourceType: ["album"],
        success: (res) => {
          this.list = [];
          this.imageList = [];
          res.tempFilePaths.forEach((item) => {
            that.imageList.push(item);
          });
          that.imageList.forEach((item) => {
            this.upImg(item);
          });
        },
      });
    },
    upImg(path) {
      uni.uploadFile({
        url: URL + `/common/upload`,
        filePath: path,
        header: {
          Authorization: `Bearer ${uni.getStorageSync("token")}`,
        },
        name: "file",
        success: (res) => {
          this.form.xgfj = JSON.parse(res.data).url;
          this.list.push(res.url);
        },
      });
    },
    //删除图片
    delectImg(i) {
      uni.showModal({
        title: "提示",
        content: "确定要删除照片吗？",
        cancelText: "取消",
        confirmText: "确定",
        success: (res) => {
          if (res.confirm) {
            this.imageList.splice(i, 1);
            this.list.splice(i, 1);
          }
          this.form.xgfj = "";
        },
      });
    },
    //点击预览图片
    previewImg(current) {
      uni.previewImage({
        current,
        urls: this.imageList, //存放图片的数组
        loop: true,
        indicator: "default",
      });
    },

    // 选择日期
    confirm(e) {
      console.log();
      this.form.yxrq = e[0] + "~" + e[e.length - 1];
      this.show = false;
    },
    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1);
      this.form.xgfj = "";
    },
    // 新增图片
    async afterRead(event) {
      // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file);
      let fileListLen = this[`fileList${event.name}`].length;
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url);
        let item = this[`fileList${event.name}`][fileListLen];
        this[`fileList${event.name}`].splice(
          fileListLen,
          1,
          Object.assign(item, {
            status: "success",
            message: "上传成功",
            url: result,
          })
        );
        fileListLen++;
      }
    },
    uploadFilePromise(url) {
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: URL + "/common/upload",
          filePath: url,
          name: "file",
          header: {
            Authorization: `Bearer ${uni.getStorageSync("token")}`,
          },
          formData: {
            user: "file",
          },
          success: (res) => {
            this.form.xgfj = JSON.parse(res.data).url;
            setTimeout(() => {
              resolve(res.data.data);
            }, 1000);
          },
        });
      });
    },

    submit() {
      this.$refs.form
        .validate()
        .then((res) => {
          uni.$u.toast("校验通过");
          add(this.form).then((res) => {
            uni.$u.toast("新增成功");
            setTimeout(() => {
              uni.navigateBack({
                delta: 1,
              });
            }, 1000);
          });
        })
        .catch((errors) => {
          uni.$u.toast("校验失败");
        });
    },
  },
};
</script>

<style lang="scss">
page {
  background-color: #f5f5f5;
}

.container {
  padding: 0 24rpx;
  background-color: #f6f6f6;

  .title {
    font-size: 28rpx;
    font-weight: 500;
    color: #999999;
    line-height: 44rpx;
    padding: 20rpx 48rpx;
  }

  .box {
    padding: 0rpx 48rpx;
    background-color: #fff;
    border-radius: 20rpx;
  }

  .textarea {
    .one {
      font-size: 28rpx;
      color: #999999;
    }

    .tarea {
      margin-top: 16rpx;
    }
  }
}

.but {
  margin: 30rpx 0;
}
</style>
